<?php
require_once 'test-00-inc.php';

start('Custom element lists');

class Test extends CxCustomElementList {
    static $index = 123;

    function current ()
    {   // PRE-PROCESSING //
        return current($this->items)->duplicate();
    }

    function process ($item)
    {   // POST-PROCESSING //
        $item['index'] = self::$index++;
        return $item;
    }

    static function fn ($item) {
        $item['index'] = self::$index++;
        echo __method__ ." got $item\r\n";
        return $item;
    }
}

test('Using custom source:','
    $test = $html->body->p[2]->append(new Test("//li"))->into($test)->items
');
foreach (nz($test) as $key => $item) {
    echo $key, " => "; var_dump($item);
}

test('Apply external function:','
    count($html->body->p[2]->apply(array("Test","fn"), "//li[not(@*)]"))
');

class TestGen implements IxElementIterator
{
    protected $template, $items;

    protected
        $data = array(
            array(1 => 'Apple'),
            array(2 => 'Banana'),
            array(9 => 'Orange')
        ),
        $map = array(
            1 => 'a',
            2 => 'b',
            9 => 'x'
        );

    /*function __construct ($data) {
        $this->data = $data;
    }*/

    function begin (IxElement $element, $self)
    {
        $this->template = $element->select('//li[@index="124"]')->items[0];
    }

    function current ()
    {   // PRE-PROCESSING //
        list($index, $text) = each(current($this->data));
        $this->template
            ->duplicate()->into($item)
            ->set_attribute('index', $index)
            ->set_value($text);
        return $item;
    }

    function process ($item)
    {   // POST-PROCESSING //
        $item['index'] = $this->map[$item['index']->value()];
        return $item;
    }

    function end ($output)
    {
        $this->items = $output;
    }

    function key ()
    {
        return key($this->data);
    }
    function next ()
    {
        next($this->data);
    }
    function rewind ()
    {
        reset($this->data);
    }
    function valid ()
    {
        return $this->key() !== null;
    }
    function count ()
    {
        return count($this->data);
    }
}

test('Using custom generator:','
    $test = $html->body->ul->append(new TestGen())
');

result($html);